package com.ztesoft.web.baseconfig.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.core.common.Page;
import com.ztesoft.core.convert.IArgConversionService;
import com.ztesoft.core.idproduce.ISequenceGenerator;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.arg.DmPlanArg;
import com.ztesoft.web.baseconfig.db.arg.DmPlanRelationArg;
import com.ztesoft.web.baseconfig.db.arg.DmPlanArg.DmPlanCriteria;
import com.ztesoft.web.baseconfig.db.arg.DmPlanRelationArg.DmPlanRelationCriteria;
import com.ztesoft.web.baseconfig.db.dao.DmPlanRelationDao;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.baseconfig.db.po.DmPlanRelationPO;
import com.ztesoft.web.baseconfig.service.IDmPlanRelationService;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.common.DMSConstant.Status;

/**
 * <Description> <br>
 * 
 * @author lin.jie<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2015年8月4日 <br>
 * @since V1.0<br>
 * @see com.ztesoft.web.baseconfig.service.impl <br>
 */

@Service("dmPlanRelationService")
public class DmPlanRelationServiceImpl implements IDmPlanRelationService {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(DmPlanRelationServiceImpl.class);

	@Autowired
	private DmPlanRelationDao dmPlanRelationDao;

	/**
	 * 查询条件转换成Arg类的服务接口
	 */
	@Resource(name = "defaultArgConversionService")
	private IArgConversionService argConversionService;

	/**
	 * 主键生成器
	 */
	@Resource(name = "sequenceProcGenerator")
	private ISequenceGenerator sequenceGenerator;

	@Override
	public DmPlanRelationPO selectByPrimaryKey(DmPlanRelationPO record) throws BaseAppException {
		return dmPlanRelationDao.selectByPrimaryKey(record);
	}

	@Override
	public List<DmPlanRelationPO> selectByArg(DmPlanRelationPO record) throws BaseAppException {
		logger.debug("selectByArg begin...record={0}", record);
		DmPlanRelationArg arg = argConversionService.invokeArg(DmPlanRelationArg.class, record);
		return dmPlanRelationDao.selectByArg(arg);
	}

	@Override
	public Page<DmPlanRelationPO> selectByArgAndPage(DmPlanRelationPO record, Page<DmPlanRelationPO> resultPage)
			throws BaseAppException {
		logger.debug("selectByArgAndPage begin...record={0}", record);
		DmPlanRelationArg arg = argConversionService.invokeArg(DmPlanRelationArg.class, record);
		resultPage = dmPlanRelationDao.selectByArgAndPage(arg, resultPage);
		return resultPage;
	}

	@Override
	public DmPlanRelationPO add(DmPlanRelationPO record) throws BaseAppException {
		logger.debug("保存计划策略关系表---record={0}", record);
		/*
		 * 替换，数据库必填，前台空值，的字段的值 所有非空字段： 不需要替换： 需要替换：
		 */
		// if (Utils.isEmpty(record.getIndexAnalyseFlag())) {
		// record.setIndexAnalyseFlag(DMSConstant.DONT_ANALYSE);
		// }
		int execOrder = 0;
		Date nowDate = new Date();
		// 通过前台传回来的ID，从数据库里找，是否已经有这条数据了
		DmPlanRelationPO dprPO = dmPlanRelationDao.selectByPrimaryKey(record);
		if (Utils.isEmpty(dprPO)) {// 不存在这条记录，说明是新增
			execOrder = getStrategyNextExecOrder(record.getDmPlanId());
			record.setExecOrder(execOrder);
			record.setCreateDate(nowDate);
			dmPlanRelationDao.insertSelective(record);
		} else {
			if (dprPO.getState().equals(Status.DRAFT.toString())) {// 草稿箱，点击提交
				// 草稿箱状态为00D或者0DA，直接修改草稿箱，状态改为00A
				dmPlanRelationDao.updateByPrimaryKeySelective(record);
			} else {// 修改，点击提交
				execOrder = getStrategyNextExecOrder(record.getDmPlanId()) - 1;
				// 先把原来的记录状态改成00X
				dprPO.setState(Status.CANCELLED.toString());
				dprPO.setStateDate(nowDate);
				dmPlanRelationDao.updateByPrimaryKeySelective(dprPO);
				// 再新增一条序号为 +1 的记录
				record.setExecOrder(execOrder);
				record.setSeqNbr(dprPO.getSeqNbr() + 1);
				record.setGroupNbr(dprPO.getGroupNbr());
				record.setStateDate(nowDate);
				record.setEffDate(dprPO.getEffDate());
				record.setCreateDate(dprPO.getCreateDate());
				dmPlanRelationDao.insertSelective(record);

			}
		}
		return record;
	}

	@Override
	public int addForDraft(DmPlanRelationPO record) throws BaseAppException {
		logger.debug("add begin...record={0}", record);
		// true:update,false:insert
		boolean isUpdate = false;
		Date nowDate = new Date();
		// 从数据库里找，是否已经有这条数据了
		DmPlanRelationPO dprPO = dmPlanRelationDao.selectByPrimaryKey(record);
		if (Utils.isEmpty(dprPO)) {// 不存在这条草稿
			isUpdate = false;
			// 获取主键
			int pkId = sequenceGenerator.sequenceIntValue("DM_PLAN", "DM_PLAN_ID");
			record.setDmPlanId(pkId);
			record.setSeqNbr(1);
		} else {
			isUpdate = true;
			record.setSeqNbr(dprPO.getSeqNbr() + 1);
		}
		record.setState(Status.DRAFT.toString());
		record.setStateDate(nowDate);
		/*
		 * 替换，数据库必填，前台空值，的字段的值
		 * 所有非空字段：dmPlanId、seqNbr、planName、effDate、expDate、createDate、state
		 * 、stateDate、cycleType
		 * 、needCheck、startTime、tableAnalyseFlag、indexAnalyseFlag
		 */
		if (Utils.isEmpty(record.getExecOrder())) {
			record.setExecOrder(DMSConstant.DRAFT_NUMBER_REPLACE);
		}
		if (Utils.isEmpty(record.getEffDate())) {
			record.setEffDate(DMSConstant.DRAFT_DATE_REPLACE);
		}
		if (Utils.isEmpty(record.getExpDate())) {
			record.setExpDate(DMSConstant.DRAFT_DATE_REPLACE);
		}
		if (Utils.isEmpty(record.getCreateDate())) {
			record.setCreateDate(DMSConstant.DRAFT_DATE_REPLACE);
		}
		// 判断执行什么操作
		if (isUpdate) {
			return dmPlanRelationDao.updateByPrimaryKey(record);
		} else {
			return dmPlanRelationDao.insertSelective(record);
		}
	}

	@Override
	public int update(DmPlanRelationPO record) throws BaseAppException {
		logger.debug("update begin...record={0}", record);
		record.setState(Status.CANCELLED.toString());
		record.setStateDate(new Date());
		dmPlanRelationDao.deleteByPrimaryKey(record);
		record.setState(Status.SUCCESS.toString());
		record.setSeqNbr(record.getSeqNbr() + 1);
		return dmPlanRelationDao.insertSelective(record);
	}

	@Override
	public int getStrategyNextExecOrder(Integer id) throws BaseAppException {
		DmPlanRelationArg arg = new DmPlanRelationArg();
		DmPlanRelationCriteria criteria = arg.createCriteria();
		criteria.andDmPlanIdEqualTo(id);
		criteria.andStateNotEqualTo(Status.CANCELLED.toString());
		arg.setOrderByClause("EXEC_ORDER DESC");
		List<DmPlanRelationPO> dprPOList = dmPlanRelationDao.selectByArg(arg);
		int result = 0;
		if (dprPOList.size() != 0) {
			result = dprPOList.get(0).getExecOrder() + 1;
		}
		return result;
	}

	@Override
	public int delete(DmPlanRelationPO record) throws BaseAppException {
		logger.debug("delete begin...record={0}", record);
		return dmPlanRelationDao.deleteByPrimaryKey(record);
	}

	@Override
	public List<DmPlanRelationPO> selectByPlanIdAndGroupNbr(Integer dmPlanId, Integer groupNbr) throws BaseAppException {

		DmPlanRelationArg arg = new DmPlanRelationArg();
		DmPlanRelationCriteria criteria = arg.createCriteria();
		if (dmPlanId != null && groupNbr != null) {
			criteria.andDmPlanIdEqualTo(dmPlanId);
			criteria.andGroupNbrEqualTo(groupNbr);
			criteria.andStateEqualTo("00A");
		}
		return dmPlanRelationDao.selectByArg(arg);
	}

	@Override
	public List<DmPlanRelationPO> selectByDmPlanId(Integer dmPlanId) throws BaseAppException {
		logger.debug("selectByDmPlan begin...record={0}");
		return dmPlanRelationDao.selectByDmPlanId(dmPlanId);
	}

	@Override
	public DmPlanRelationPO selectBySourceDataId(Integer sourceDataId) throws BaseAppException {
		return dmPlanRelationDao.selectBySourceDataId(sourceDataId);
	}

}
